package com.jing.cloud.service.chat.websocket;

import com.jing.cloud.service.chat.constant.ChatConstant;
import com.jing.cloud.service.chat.model.SessionCache;
import com.jing.cloud.service.user.bean.Ticket;
import com.jing.cloud.service.user.dao.TicketDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;

/**
 * Created by 29017 on 2017/9/8.
 */
@Component
@Slf4j
public class ChatHandshakeInterceptor extends HttpSessionHandshakeInterceptor {

    @Autowired
    private TicketDao ticketDao;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest httpRequest = (ServletServerHttpRequest) request;
            try {
                String clientIp = httpRequest.getRemoteAddress().toString();
                String ticket = httpRequest.getServletRequest().getParameter("ticket");
                long messageId = Long.valueOf(httpRequest.getServletRequest().getParameter("messageId"));
                Ticket t = ticketDao.getByTicketStr(ticket);
                if (null != t) {
                    long userId = t.getUserId();
                    SessionCache cache = new SessionCache();
                    cache.setUserId(userId);
                    cache.setTicket(ticket);
                    cache.setDeviceType(t.getDeviceType());
                    cache.setMessageId(messageId);
                    attributes.put(ChatConstant.SESSION_CACHE_ATTR_STR, cache);
                    log.info("webSocket connecting. client:[{}] param:[{}]", clientIp, cache);
                    return true;
                }

            } catch (Exception e) {
                log.error("beforeHandshake fail", e);
            }
        }

        return false;
    }
}
